package cn.itcast.netty.basic;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * 服务器端的业务处理
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    //读取数据事件
    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object meg)  {
        System.out.println("server:"+channelHandlerContext);
        ByteBuf buf =  (ByteBuf) meg;

        System.out.println("客户端发来的消息："+ buf.toString(CharsetUtil.UTF_8));
    }

    //数据读取完事件
    @Override
    public void channelReadComplete(ChannelHandlerContext channelHandlerContext)  {
        channelHandlerContext.writeAndFlush(Unpooled.copiedBuffer("没钱了！", CharsetUtil.UTF_8));
    }

    //异常发生事件
    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable throwable) {
        channelHandlerContext.close();
    }
}
